<template>
  <div>
    <h1>三级分类列表</h1>
    <el-switch
  v-model="value"
  active-color="#13ce66"
  inactive-color="#ff4949">
</el-switch>
    <el-tree
    v-if="value"
     :allow-drop="allowDrop"
      @node-drop="nodeDrop"
      :draggable="true"
      node-key="catId"
      :default-expanded-keys="expandedkeys"
      :expand-on-click-node="false"
      :data="data"
      :props="defaultProps"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="data.catLevel != 3"
            type="text"
            size="mini"
            @click="
              category = { sort: 0 };
              append(data);
            "
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            update
          </el-button>
          <el-button
            type="text"
            v-if="node.childNodes.length == 0"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
      <el-form :model="category">
        <el-form-item label="分类名称" label-width="120px">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value:true,
      updateNodes:[], //需要和数据库同步的对象
      pid:0,
      level:1,
      defultExpandedKeys:[],
      countLevel: 1,
      expandedkeys: [],
      category: {
        sort: 0,
      },
      dialogFormVisible: false,
      data: [],
      defaultProps: {
        label: "name",
      },
    };
  },
  components: {},
  created() {
    this.getDataList();
  },
  activated() {},
  methods: {
    
  
    /**
     * 拖拽成功时触发的事件
     * draggingNode, 被拖拽的对象
     * dropNode 目标对象
     * 
     * type 拖拽类型before、after、inner
     * 在当前方法中需要把数据传递到后台和数据库交互改变数据库的数据
     * 传什么对象给数据库
     * 拖拽成功后数据库的哪些字段需要改变
     * catId
     * name parentId
     * sort
     */
    nodeDrop(draggingNode, dropNode, type){
        if(type=="after" || type=="before"){
          //pid 赋值
           this.pid=dropNode.data.parentCid;
           //层级变成目标对象的层级
           this.level=dropNode.data.catLevel
           //sort 目标对象父元素的子元素集合的下标
           //开始收集元素
           /**
            * 第一个参数为目标对象的父元素的子元素集合
            */
           if(draggingNode.data.catLevel!=dropNode.data.catLevel){
             //需要收集被拖拽对象的子元素
             this.collectNodes(dropNode.parent.childNodes,this.level,this.pid,true,draggingNode);
           }else{
           this.collectNodes(dropNode.parent.childNodes,this.level,this.pid)         
           }     
        }else if(type=="inner"){
          //pid 目标对象的id
             this.pid=dropNode.data.catId
             //catlevel 目标对象层级+1
             this.level=dropNode.data.catLevel+1;
             //第一个参数为目标对象的子元素
             this.collectNodes(dropNode.childNodes,this.level,this.pid)
        } 
        console.log("数据库同步的对象:",this.updateNodes)
             this.$http({
        url: this.$http.adornUrl(`/product/category/updateNodes`),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "拖拽成功",
            type: "success",
            duration: 1500,
          });
          this.dialogFormVisible = false;
          this.getDataList();
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    /**
     * 需要被收集的集合
     */
    collectNodes(nodes,level,pid,flag=false,node2){
       console.log("需要被收集的集合为:",nodes)
       for (var i = 0; i < nodes.length; i++) {
         var obj= {
           catId:nodes[i].data.catId,
           name:nodes[i].data.name,
           parentCid:pid,
           catLevel:level,
           sort:i
         }
          this.updateNodes.push(obj)
 
       }
       if(flag){
         this.collectNodes(node2.childNodes,this.level+1,node2.data.catId);
       }
    },
    /**
     * 判断节点是否能拖拽
      draggingNode  被拖拽的对象
      dropNode   目标对象
      type 拖拽类型
      目标对象能否放置被拖拽的对象
      1.1 计算被拖拽的层数
      1.2 层数和目标对象的层数 判断是否大于3
      2  判断是否大于3
     */
    allowDrop(draggingNode, dropNode, type){
      this.getCountLevel(draggingNode)
      console.log("这是被拖拽的层级为:"+this.countLevel)
      //根据计算好的层级判断总层数不能大于3
      if(type=="next"||type=="prev"){
          if(this.countLevel==3&&dropNode.level==1) return true;
          if(this.countLevel==2&&dropNode.level!=3) return true;
          if(this.countLevel==1) return true;    
      }else if(type=="inner"){
          if(this.countLevel==2&&dropNode.level==1) return true;
          if(this.countLevel==1&&dropNode.level!=3) return true;
      }
        return false
    },
    //计算层级
    getCountLevel(node){
      this.countLevel=1
      if(node.childNodes.length!=0){
        this.countLevel=2;
        for(var i in node.childNodes){
          if(node.childNodes[i].childNodes!=0){
            this.countLevel=3
            return;
          }
        }
      }
         console.log()
    },
    //保存
    save() {
      let methodUrl = "save";
      if (this.category.catId) {
        methodUrl = "update";
      }
      this.$http({
        url: this.$http.adornUrl(`/product/category/${methodUrl}`),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
          this.dialogFormVisible = false;
          this.getDataList();
          this.expandedkeys = [this.category.parentCid];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    remove(node, data) {
      let ids = [data.catId];
      this.$http({
        url: this.$http.adornUrl(`/product/category/delete`),
        method: "post",
        data: this.$http.adornData(ids, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
          this.dialogFormVisible = false;
          this.getDataList();
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    //回显
    update(data) {
      this.dialogFormVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.category = data.category;
      });
    },
    append(data) {
      this.dialogFormVisible = true;
      (this.category.parentCid = data.catId),
        (this.category.catLevel = data.catLevel + 1);
    },
    getDataList() {
      this.dataListLoading = true;

      this.$http({
        url: this.$http.adornUrl("/product/category/tree/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.data = data.data;
      });
    },
  },
};
</script>
